package com.nondo.dean.saprfc.service;

import com.google.common.collect.ImmutableList;
import com.nondo.dean.saprfc.common.SapUtil;
import com.nondo.dean.saprfc.common.Util;
import com.nondo.dean.saprfc.domain.OrderSubjectDetailResult;
import com.nondo.dean.saprfc.domain.OrderSubjectResult;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

/**
 * @author xiaofan
 * @Description: 将订单传输到sap
 * @throws
 * @date 2018-04-2715:44
 * @Version 0.1
 */
@Component
public class CrmOrderTransmitService {
    private static final Logger logger = LoggerFactory.getLogger(SapUtil.class);

    /**
     *   分销渠道
     */
    private static final String CHANNEL_DISTRIBUTION_COMMERCE="40";
    private static final String CHANNEL_DISTRIBUTION_DEALER="20";
    private static final String CHANNEL_DISTRIBUTION_CHAINSTORE="10";
    private static final String CHANNEL_DISTRIBUTION_SIXTY="60";
    private static final String CHANNEL_CUSTOMER_COMMERCE="B330001";
    private static final String CHANNEL_CUSTOMER_DEALER="B330002";
    private static final String CHANNEL_CUSTOMER_CHAINSTORE="A000000";

    private static final String NULL_TO_STRING = "";
    private static final String JUDGE_SOFTWARE_DESIGNATION="软体";
    /**
     * sap消息校验
     */
    private static final String MESSAGE_SUCCESS_MARK="RIGHT";
    private static final String MESSAGE_ERROR_MARK="MSG_ERR";
    private static final String SAP_OREDER_CODE="SapOrder";

    ImmutableList<String> diansList =ImmutableList.of(CrmOrderTransmitService.CHANNEL_CUSTOMER_COMMERCE, CrmOrderTransmitService.CHANNEL_CUSTOMER_DEALER);

    /**
     * 判断分销渠道
     * @param crmCode
     * @return
     */
    public String judgeChannelOfDistribution(String crmCode){
        //40电商，20 经销商
        String customerCode=diansList.contains(crmCode) ? CrmOrderTransmitService.CHANNEL_DISTRIBUTION_COMMERCE : CrmOrderTransmitService.CHANNEL_DISTRIBUTION_DEALER;
        if(CrmOrderTransmitService.CHANNEL_CUSTOMER_CHAINSTORE.equals(crmCode)){
            //10 直营店
            customerCode = CrmOrderTransmitService.CHANNEL_DISTRIBUTION_CHAINSTORE;
        }
        if(crmCode.startsWith("B60")){
            customerCode = CrmOrderTransmitService.CHANNEL_DISTRIBUTION_SIXTY;
        }
        return customerCode;
    }

    /**
     *订单传输
     * @param orderResult
     * @return
     */
    public Map<String ,String> orderSynSap(OrderSubjectResult orderResult,String sapCilent){
        //数量合计
        double tmpNum=0;
        JCoFunction function = SapUtil.getFunction(sapCilent,"Z_ND_OA_SD_CREATE_SO");

        logger.info("function="+function);
        //操作人员
        function.getImportParameterList().setValue("IM_ERNAM",orderResult.getSapAccount());
        logger.info("function.getImportParameterList()="+function.getImportParameterList());
        //订单总价
        function.getImportParameterList().setValue("IM_NETPR",orderResult.getAmount());
        JCoStructure IS_HEADER = function.getImportParameterList().getStructure("IS_HEADER");
        JCoTable IT_ITEM = function.getTableParameterList().getTable("IT_ITEM");

        //订单主体
        synOrderSubject(orderResult,IS_HEADER);
        //订单明细
        for(OrderSubjectDetailResult detailResult : orderResult.getOrderSubjectDetailResultList()){
            //数量合计
            tmpNum+=detailResult.getPurchaseQuantity();

            if(detailResult.getUpId() !=0 && (!detailResult.getUpCode().startsWith("D")&& ! detailResult.getUpCode().startsWith("ZD")))continue;

            synOrderDetail(detailResult,IT_ITEM);
        }

        Map<String ,String> resMap = execute(function,orderResult,sapCilent,tmpNum);

        return resMap;
    }

    /**
     * 执行传输方法
     * @param function
     * @param sapCilent
     * @param tmpNum
     * @return
     */
    public Map<String ,String> execute(JCoFunction function,OrderSubjectResult orderResult,String sapCilent,double tmpNum){
        String right = CrmOrderTransmitService.NULL_TO_STRING;String error = CrmOrderTransmitService.NULL_TO_STRING;
        Map<String ,String> messMap = new HashedMap();
        try {
            function.execute(SapUtil.getDestination(sapCilent));
            //sap消息标示 X 创建失败
            String cpEind = function.getExportParameterList().getString("CP_EIND");
            //sap返回的订单号
            String vbeln = function.getExportParameterList().getString("VBELN");
            //sap的总金额
            double sap_amount = function.getExportParameterList().getDouble("NETWR");
            //sap的订单总数量
            double sapQuantity = function.getExportParameterList().getDouble("MENGE");
            //sap返回的消息
            JCoTable liReturn = function.getTableParameterList().getTable("LT_RETURN");
            if(CrmOrderTransmitService.NULL_TO_STRING.equals(cpEind) && !CrmOrderTransmitService.NULL_TO_STRING.equals(vbeln)){

                messMap.put(CrmOrderTransmitService.SAP_OREDER_CODE,vbeln);
                right="已成功传输Sap";
                if(Math.abs(orderResult.getAmount().doubleValue() - sap_amount)>=1){
                    right+="订单总金额存在差异,请检查!<br/>SAP订单金额为:"+sap_amount+"元,　订单金额为:"+orderResult.getAmount()+"元　差异金额为:"+(sap_amount-orderResult.getAmount().doubleValue())+"";
                }
                if(Math.abs(tmpNum - sapQuantity)>0){
                    right+="订单总数量存在差异,请检查!<br/>SAP订单总数量为:"+sapQuantity+"个 ,　订单总数量为:"+tmpNum+"个　差异数量为:"+(sapQuantity - tmpNum)+"";
                }
                right += SapUtil.writeSapMessage(liReturn);
            }else if("X".equals(cpEind)){
                error = "订单创建失败！";
                error += SapUtil.writeSapMessage(liReturn);
            }
            messMap.put(CrmOrderTransmitService.MESSAGE_SUCCESS_MARK,right);
            messMap.put(CrmOrderTransmitService.MESSAGE_ERROR_MARK,error);
        } catch (JCoException e) {
            logger.info(e.getMessage());
            logger.info(e.getLocalizedMessage());
        }


        return messMap;
    }

    /**
     * 订单主体传输
     * @param orderResult
     * @param IS_HEADER
     */
    public void synOrderSubject(OrderSubjectResult orderResult,JCoStructure IS_HEADER){
        //事业部代码
        IS_HEADER.setValue("VKORG", orderResult.getBusinessCode());
        // 分销渠道
        IS_HEADER.setValue("DISTR_CHAN",  judgeChannelOfDistribution(orderResult.getUserNo()));
        // 产品组
        IS_HEADER.setValue("DIVISION", "10");
        // 客户编号
        IS_HEADER.setValue("PARTN_NUMB", orderResult.getUserNo());
        // 客户采购订单号
        IS_HEADER.setValue("PURCH_NO_C", orderResult.getOrderCode());
        //导购员
        IS_HEADER.setValue("OYSHO", orderResult.getSaleGuide());
        //客户等级
        IS_HEADER.setValue("CU_CLASS",orderResult.getUserType());
        //客户电话
        IS_HEADER.setValue("CU_TELF1", orderResult.getUserTelphone());
        //客户姓名
        IS_HEADER.setValue("CU_NAME", orderResult.getUserName());
        //客户下单日期
        IS_HEADER.setValue("CU_DATE", orderResult.getCreateDate());
        //下单合同编号
        IS_HEADER.setValue("CU_NUMB", orderResult.getContract());
        //运输员
        IS_HEADER.setValue("TRANS", orderResult.getDeliveryUser());
    }

    /**
     * 异型调价
     * @param detailResult
     * @return
     */
    public double differentCalculation(OrderSubjectDetailResult detailResult){
        BigDecimal  divisionResults=new BigDecimal(0);
        //异型调价
        BigDecimal specialPrice = detailResult.getSpecialPrice();
        BigDecimal purchaseQuantity=new BigDecimal(1);//子件数量
        if(detailResult.getPurchaseQuantity()!=0){
            purchaseQuantity= BigDecimal.valueOf(detailResult.getPurchaseQuantity());
        }
        if(specialPrice.intValue() != 0){
            divisionResults=specialPrice.divide(purchaseQuantity,RoundingMode.HALF_UP);
        }
        return divisionResults.doubleValue();
    }
    /**
     * 产品明细传输
     * @param detailResult
     * @param IT_ITEM
     */
    public void  synOrderDetail(OrderSubjectDetailResult detailResult,JCoTable IT_ITEM){

        String productCode=detailResult.getProductCode();

        if(Util.isNumber(productCode)==true){
            //产品编号补0
            productCode=Util.lpad(productCode, 18);
        }
        if(CrmOrderTransmitService.JUDGE_SOFTWARE_DESIGNATION.equals(detailResult.getProdisrt()) && (! detailResult.getProductCode().startsWith("AP0") && ! detailResult.getProductCode().startsWith("BD"))){
            for (int i = 1; i <= detailResult.getPurchaseQuantity(); i++) {
                IT_ITEM.appendRow();
                IT_ITEM.setValue("MATERIAL", productCode);// 产品编号
                IT_ITEM.setValue("TARGET_QTY", "1");// 数量
                IT_ITEM.setValue("COND_VALUE", differentCalculation(detailResult));// 异形调价价格
                IT_ITEM.setValue("L_POSNR", detailResult.getPoItem());//PO行项目
                IT_ITEM.setValue("WENBEN", detailResult.getNote());//异形备注
            }
        }else{
            if(detailResult.getUpId()!=0){//自动带出的子件标识 不传入数量
                detailResult.setPurchaseQuantity(0);
            }
            IT_ITEM.appendRow();
            IT_ITEM.setValue("MATERIAL", productCode);// 产品编号
            IT_ITEM.setValue("TARGET_QTY", detailResult.getPurchaseQuantity());// 数量
            IT_ITEM.setValue("COND_VALUE", differentCalculation(detailResult));// 异形调价价格
            IT_ITEM.setValue("L_POSNR", detailResult.getPoItem());//PO行项目
            IT_ITEM.setValue("WENBEN", detailResult.getNote());//异形备注
        }

    }
}
